package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.IPangXieApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/20 14:07
 */
@Slf4j
@Service
public class PangXieApiImpl implements IPangXieApi {

    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    @Resource
    private IGameAttributeService gameAttributeService;

    @Resource
    private ArtRecMapper artRecMapper;

    @Autowired
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    public static void main(String[] args) {
        String apiKey = "6a112ce0db7a07104e3ad9fa16d048a5";
        Map<String, Object> params = new HashMap<>();
        params.put("type", "add");
        params.put("product_id", "123");
        Map<String, Object> data = new TreeMap<>();
        data.put("name", "测试");
        data.put("price", "100");
        data.put("content", "内容");
        data.put("image", "图片");
        data.put("daqu", "1");
        data.put("shuliang", "10");
        long time = new Date().getTime();
        data.put("add_time", time);
        data.put("fangchenmi", "0");


        data.put("shiming", "0");
        data.put("apiKey", apiKey);

        StringBuffer resut = new StringBuffer();
        for (String key : data.keySet()) {
            System.out.println("key= " + key + " and value= " + data.get(key));
            if (!"content".equals(key)) {
                resut.append(data.get(key));
            }
        }
        System.out.println(resut);
        String sign = DigestUtils.sha1Hex(resut.toString());

        params.put("data", data);
        params.put("sign", sign);
        String shangjia_id = "zyl";
        params.put("shangjia_id", shangjia_id);
        params.put("unique_no_shangjia", "1111");
        String paramsStr = JSONObject.toJSONString(params);
        String url = "http://api-shangjia.pxb7.com/api/product_wzry_v2.php";
        System.out.println("请求参数=" + paramsStr);
        String res = HttpUtils.sendPost(url, paramsStr, "application/json");
        System.out.println("返回参数=" + res);
        String message = JSONObject.parseObject(res).getString("message");
        String s = MapUntils.unicodeToString(message);
        System.out.println("返回参数=" + s);
    }


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "add", salePartner);
        params.remove("apiKey");
        log.info("螃蟹添加接口请求参数={}", JSONObject.toJSONString(params));
        String url = "";


        if (Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_wzry_v2.php");
        } else if (Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_hpjy_v2.php");
        } else if (Objects.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_yxlm_v2.php");
        } else {
            throw new GlobalException("螃蟹暂不支持此游戏");
        }


        String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params), "application/json");
        log.info("螃蟹添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String message = resultJson.getString("message");
        message = MapUntils.unicodeToString(message);

        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String reaccount_id = resultJson.getString("id");
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setOutid(reaccount_id);
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if (org.springframework.util.CollectionUtils.isEmpty(artRecs)) {
                ArtRec artRec = new ArtRec();
                artRec.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRec.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRec.setType(LCConstant.interAdd);
                artRec.setConfig(salePartner.getId());
                artRec.setSaleCode(salePartner.getSaleName());
                artRec.setOutid(reaccount_id);
                artRecMapper.insertArtRec(artRec);
            }
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", message);
        return AjaxResult.success(result);

    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,
                               SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "update", salePartner);
        params.remove("apiKey");
        log.info("螃蟹编辑接口请求参数={}", JSONObject.toJSONString(params));
        String url = "";
        if (Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_wzry_v2.php");
        } else if (Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_hpjy_v2.php");
        } else if (Objects.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
            url = OutUrlConstant.PXXURL.replace("base", "product_yxlm_v2.php");
        } else {
            throw new GlobalException("螃蟹暂不支持此游戏");
        }

        String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params), "application/json");
        log.info("螃蟹编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String message = resultJson.getString("message");
        message = MapUntils.unicodeToString(message);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", message);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,  SalePartner
            salePartner) {
        if (null != goodsInfoAndAttrValueDto) {
            String url = "";
            if (Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
                url = OutUrlConstant.PXXURL.replace("base", "product_wzry_v2.php");
            } else if (Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
                url = OutUrlConstant.PXXURL.replace("base", "product_hpjy_v2.php");
            } else if (Objects.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
                url = OutUrlConstant.PXXURL.replace("base", "product_yxlm_v2.php");
            } else {
                throw new GlobalException("螃蟹暂不支持此游戏");
            }
//            String outId = reOutId(goodsInfoAndAttrValueDto, salePartner);
            Map<String, Object> params = new HashMap<>();
            params.put("type", "delete");
            params.put("product_id", goodsInfoAndAttrValueDto.getId());


            StringBuffer resut = new StringBuffer();
            for (String key : params.keySet()) {
                if (!"content".equals(key)) {
                    resut.append(params.get(key));
                }
            }
            String sign = salePartner.getSaleKey() + goodsInfoAndAttrValueDto.getId();
            sign = DigestUtils.sha1Hex(sign);
            params.put("sign", sign);

            params.put("unique_no_shangjia", goodsInfoAndAttrValueDto.getId());
            params.put("shangjia_id", salePartner.getOther());
            log.info("螃蟹删除接口请求参数={}", JSONObject.toJSONString(params));
            String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params), "application/json");
            log.info("螃蟹删除接口返回参数={}", response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String message = resultJson.getString("message");
            message = MapUntils.unicodeToString(message);
            Map<String, Object> result = new HashMap<>();
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                artRecMapper.deleteArtRecCode(goodsInfoAndAttrValueDto.getId(), salePartner.getId());
            }
            result.put("req", JSONObject.toJSONString(params));
            result.put("res", response);
            result.put("msg", message);
            return AjaxResult.success(result);
        } else {
            throw new GlobalException("删除ID未查询到此数据");
        }
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String type, SalePartner
            sa) {

        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("product_id", String.valueOf(goodsInfoAndAttrValueDto.getId()));
        Map<String, Object> data = new TreeMap<>();
        String smFN = "";


        if (goodsInfoAndAttrValueDto.getPrice().compareTo(new BigDecimal(1000)) < 0) {
            goodsInfoAndAttrValueDto.setPrice(goodsInfoAndAttrValueDto.getPrice().add(new BigDecimal(100)));
        }

        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), sa);
        data.put("price", bigDecimal);


        StringBuffer imgs = new StringBuffer();
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> goodsInfoImgList = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if (!CollectionUtils.isEmpty(goodsInfoImgList)) {
            for (GoodsInfoImg img : goodsInfoImgList) {
                String imgStr = img.getImgUrl() + " ";
                imgs.append("<img src=" + imgStr + "/>");
            }
        }
        String content = "<h3>" + goodsInfoAndAttrValueDto.getDes() + "</h3>";
        data.put("content", content + imgs.toString());
        String titleImg = goodsInfoAndAttrValueDto.getTitleImg();
        if (!StringUtils.isNull(titleImg)) {
            data.put("image", titleImg);
        } else if (!org.springframework.util.CollectionUtils.isEmpty(goodsInfoImgList)) {
            data.put("image", goodsInfoImgList.get(0).getImgUrl());
        } else {
            data.put("image", this.salePartner.getTwoOther());
        }
        if (StringUtils.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            switch (goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName()) {
                case "安卓QQ":
                    data.put("daqu", 1);
                    break;
                case "安卓微信":
                    data.put("daqu", 2);
                    break;
                case "苹果QQ":
                    data.put("daqu", 3);
                    break;
                case "苹果微信":
                    data.put("daqu", 4);
                    break;
            }
            int skins = 0;
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF8())) {
                skins = Integer.parseInt(goodsInfoAndAttrValueDto.getF8());
            }
            if (skins < 50) {
                data.put("shuliang", "0");
            } else if (50 < skins && skins <= 100) {
                data.put("shuliang", "1");
            } else if (100 < skins && skins <= 150) {
                data.put("shuliang", "2");
            } else if (150 < skins && skins <= 200) {
                data.put("shuliang", "3");
            } else if (200 < skins && skins <= 250) {
                data.put("shuliang", "4");
            } else if (250 < skins && skins <= 300) {
                data.put("shuliang", "5");
            } else if (300 < skins && skins <= 311) {
                data.put("shuliang", "6");
            } else {
                data.put("shuliang", "6");
            }
            data.put("fangchenmi", "0");
            smFN = reRedioValue(goodsInfoAndAttrValueDto.getF16());
            if (StringUtils.equals(smFN, "可二次实名") || StringUtils.equals(smFN, "已删实名")) {
                data.put("shiming", "0");
            } else {
                data.put("shiming", "1");
            }
        } else if (StringUtils.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            switch (goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName()) {
                case "安卓QQ":
                    data.put("daqu", 1);
                    break;
                case "安卓微信":
                    data.put("daqu", 2);
                    break;
                case "苹果QQ":
                    data.put("daqu", 3);
                    break;
                case "苹果微信":
                    data.put("daqu", 4);
                    break;
            }
            smFN = reRedioValue(goodsInfoAndAttrValueDto.getF10());
        } else if (StringUtils.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
            switch (goodsInfoAndAttrValueDto.getGroupName()) {
                case "电信":
                    data.put("daqu", 1);
                    break;
                case "网通":
                    data.put("daqu", 2);
                    break;
                case "教育网专区":
                    data.put("daqu", 6);
                    break;
                case "峡谷之巅":
                    data.put("daqu", 4);
                    break;
            }
            smFN = reRedioValue(goodsInfoAndAttrValueDto.getF1());
        }
        data.put("name",
                "【" + goodsInfoAndAttrValueDto.getId() + "】 " + smFN + "  " + goodsInfoAndAttrValueDto.getDes());

        long time = DateUtils.getNowDate().getTime();
        data.put("add_time", time / 1000);
        data.put("apiKey", this.salePartner.getSaleKey());

        StringBuffer resut = new StringBuffer();
        for (String key : data.keySet()) {
            if (!"content".equals(key)) {
                resut.append(data.get(key));
            }
        }
        String sign = DigestUtils.sha1Hex(resut.toString());
        params.put("sign", sign);

        data.remove("apiKey");
        params.put("data", data);
        params.put("shangjia_id", this.salePartner.getOther());
        params.put("unique_no_shangjia", String.valueOf(goodsInfoAndAttrValueDto.getId()));
        return params;
    }

    private String reRedioValue(String value) {
        String reStr = "";
        if (StringUtils.isNotEmpty(value)) {
            GameAttribute gameAttribute =
                    gameAttributeService.selectGameAttributeById(Long.valueOf(value));
            if (gameAttribute != null) {
                if (StringUtils.isNotEmpty(gameAttribute.getFieldName())) {
                    reStr = gameAttribute.getFieldName();
                }

            }
        }
        return reStr;
    }

    /**
     * 返回outId
     *
     * @param goodsInfoAndAttrValueDto
     * @param salePartner
     * @return
     */
    private String reOutId(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String outId = "";
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (CollectionUtils.isNotEmpty(artRecs)) {
            if (artRecs.size() == 1) {
                outId = artRecs.get(0).getOutid();
            } else {
                throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                        "下outId为多个,请查看");
            }
        } else {
            throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                    "下outId未找到,请查看");
        }
        return outId;
    }
}

